package com.skillworld.webapp.model.team;

import java.sql.Time;
import java.util.List;

import com.skillworld.webapp.model.team.Team;
import com.skillworld.webapp.model.team.TeamDao;
import com.skillworld.webapp.model.util.dao.GenericDaoHibernate;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.skillworld.webapp.model.team.Team;
import com.skillworld.webapp.model.team.TeamDao;
import com.skillworld.webapp.model.tutorial.Tutorial;
import com.skillworld.webapp.model.util.dao.GenericDaoHibernate;

@Repository("TeamDao")
public class TeamDaoHibernate extends GenericDaoHibernate<Team,Long> implements TeamDao
{
    public boolean existsByName(String name)
    {
        return getSession().createQuery("SELECT t.teamId FROM Team t " +
                  "WHERE UPPER(t.name) = UPPER(:name)")
                  .setParameter("name", name) 
                  .uniqueResult() != null;
    }
    
    private Criteria buildSearchQuery(List<String> keywords)
    {

        Criteria q = getSession().createCriteria(Team.class);

        for (String k : keywords) 
        {
            Criterion inName = Restrictions.ilike("name", k, MatchMode.ANYWHERE);
            Criterion inInfo = Restrictions.ilike("info", k, MatchMode.ANYWHERE);

            q.add(Restrictions.or(inName,inInfo));
        }

        return q;
    }
    
    @SuppressWarnings("unchecked")
    public List<Team> searchTeams(List<String> keywords, 
                                int startIndex, int count)
    {
        return(List<Team>) buildSearchQuery(keywords)
                                .addOrder(Order.asc("name"))
                                .setFirstResult(startIndex)
                                .setMaxResults(count)
                                .list();
    }
    
    public long numberOfTeams(List<String> keywords)
    {
        return(Long) buildSearchQuery(keywords)
                        .setProjection(Projections.rowCount())
                        .uniqueResult();
    }
    
    @SuppressWarnings("unchecked")
    public List<Team> topTeams(int count)
    {
        return(List<Team>) getSession().createQuery(
                                    "SELECT t FROM Team t " +
                                    "ORDER BY t.points DESC")
                                        .setFirstResult(0)
                                        .setMaxResults(count)
                                        .list();
    }
}
